package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * <desc>
 *      禁用物业账号时，删除物业账号缓存消费者
 * </desc>
 *
 * @createDate 2017/10/17
 */
@Component
public class RemoveRedisWhenDiableUserConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(RemoveRedisWhenDiableUserConsumer.class);
    @Autowired
    private RedisService<Object> deleteCacheRedisService;
    /**
     * <desc>
     *      删除缓存消费者
     * </desc>
     * @param message 消息
     * @param channel
     * @author Biao.R
     * @createDate 2017/11/11
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_DELETE_CACHE_QUEUE)
    public void process(Message message, Channel channel) throws IOException {
        byte[] body = message.getBody();
        //LOG.info("RabbitMQ_禁用物业账号时，删除物业账号缓存消费者:" + body);
        try {

            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JsonUtil.toObject(new String(body),
                    TimeTaskDeadMessageQueuePO.class);
            JSONObject jsonObject = JSON.parseObject(timeTaskDeadMessageQueuePO.getMessageContent());
            List<String> cacheKeyList = JSON.parseObject(JSON.toJSONString(jsonObject.get("data")),
                    ArrayList.class);
            if (cacheKeyList != null && !cacheKeyList.isEmpty()) {
                for (String cacheKey : cacheKeyList) {
                    deleteCacheRedisService.del(cacheKey);
                }
            }
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            LOG.error("【RabbitMQ_禁用物业账号时，删除物业账号缓存消费者】:处理异常", e);
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
